/* eslint-disable */
import qs from 'qs';
import url from 'url';
import { REG_URL } from 'constants/regexp';

const isProduction = process.env.NODE_ENV === 'production';

const domains = {
    dev: {
        h5: 'http://www.zhihu.com',
    },
    test: {
        h5: 'http://www.baidu.com',
    },
    prod: {
        h5: 'http://www.baidu.com',
    },
};

const env = process.env.VUE_APP_CURRENTMODE;
const getDomainByEnv = domains[env];
const location = global.location || {};

function createURL(options, query) {
    const { URL = options } = options;
    if (REG_URL.test(URL) || /^\//.test(URL)) return URL;

    const [, domain, pathname, search] = /^([\w|-]+):?([\w|/|-]+)?(.*)?$/iu.exec(URL);
    const origin = getDomainByEnv[domain];
    if (origin) {
        const source = url.parse(origin);
        const protocol = isProduction ? String(location.protocol).replace(/:$/, '') : 'http';
        const config = url.parse(url.format({ ...source, protocol, pathname, search }));
        if (query) {
            const queryString = {
                ...qs.parse(config.query),
                ...query,
            };
            config.query = qs.stringify(queryString);
            config.search = `?${config.query}`;
        }

        return url.format(config);
    }

    return URL;
}

export default createURL;
